<template>
  <div class="wft-dynamic-comp-senior-form">
    <van-form :ref="attrs.ref" :label-width="attrs.labelWidth" :label-align="attrs.labelAlign" :disabled="attrs.disabled">
      <component
        v-for="(comp, index) in curComp.children"
        :key="comp.id"
        :is="`${comp.compKey}Temp`"
        :curComp="comp"
        :data="comp.data"
        @submitForm="submitForm"
      />
    </van-form>
  </div>
</template>
<script>
import useRequestMixin from '../../mixins/useRequest'
import useAttrsMixin from '../../mixins/useAttrs'
export default {
  mixins: [useRequestMixin, useAttrsMixin],
  props: {
    curComp: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    'curComp.data': {
      handler() {
        this.fillData()
      },
      deep: true
    }
  },
  methods: {
    // 数据回显
    fillData() {
      this.curComp.children.forEach(item => {
        item.data.data = this.curComp.data[item.field] || ''
      })
    },
    // 表单提交
    submitForm(server) {
      let url = server.config.url
      let method = server.config.method
      let headers = this.getOptions(server.config.headers)
      let params = this.getOptions(server.config.params)
      let data = this.getOptions(server.config.body)
      this.curComp.children.forEach(item => {
        data[item.field] = item.data.data
      })
      request({ url, method, headers, params, data }).then(res => {
        if(!server.handler) {
          return this.$message.success('提交成功!')
        }
        const func = new Function('res', server.handler)
        func.call(this, res)
      })
    },
    getOptions(data) {
      const target = {}
      data.forEach(item => {
        try {
          target[item.key] = JSON.parse(item.value)
          if(typeof target[item.key] !== 'object') {
            target[item.key] = String(target[item.key])
          }
        }catch(e) {
          target[item.key] = item.value
        }
      })
      return target
    }
  }
}
</script>
<style scoped>
.wft-dynamic-comp-senior-form {
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
}
</style>
